package x.java.awt;

import java.awt.Component;
import java.io.FilenameFilter;

import x.javax.swing.JFileChooser;

/**
 * A JFileChooser in FileDialog's clothing
 * 
 * @author qiangli
 *
 */
public class FileDialog extends x.javax.swing.JFileChooser {
	public static final int LOAD = java.awt.FileDialog.LOAD;
	public static final int SAVE = java.awt.FileDialog.SAVE;
	//
	private int mode = LOAD;
	private Component parent = null;
	private FilenameFilter filter = null;

	private static final long serialVersionUID = 1L;

	private int rc;
	
	public FileDialog(Component parent) {
		this(parent,"",LOAD);
	}

	public FileDialog(Component parent, String title) {
		this(parent,title,LOAD);
	}

	public FileDialog(Component parent, String title, int mode) {
		this.parent = parent;
		super.setDialogTitle(title);
		int dialogType = (mode == SAVE) ? javax.swing.JFileChooser.SAVE_DIALOG:javax.swing.JFileChooser.OPEN_DIALOG;
		super.setDialogType(dialogType);
		super.setMultiSelectionEnabled(false);
		super.setFileSelectionMode(JFileChooser.FILES_ONLY);
	}

	public String getDirectory() {
		return super.getCurrentDirectory().getAbsolutePath();
	}

	public String getFile() {
		java.io.File f = super.getSelectedFile();
		if (f != null && rc == JFileChooser.APPROVE_OPTION) {
			return f.getName();
		}
		return null;
	}

	public void setDirectory(String dir) {
		super.setCurrentDirectory(new x.java.io.File(dir));
	}

	public void setFile(String file) {
		super.setSelectedFile(new x.java.io.File(getDirectory(),file));
	}

	public void addNotify() {
		super.addNotify();
	}

	public FilenameFilter getFilenameFilter() {
		return filter;
	}

	public int getMode() {
		return mode;
	}

	protected String paramString() {
		return super.paramString();
	}

	public synchronized void setFilenameFilter(FilenameFilter filter) {
		this.filter = filter;
		super.setFileFilter(new MyFileFilter(filter));
	}

	public void setMode(int mode) {
		this.mode = mode;
		int dialogType = (mode == SAVE) ? javax.swing.JFileChooser.SAVE_DIALOG:javax.swing.JFileChooser.OPEN_DIALOG;
		super.setDialogType(dialogType);
	}

	/**
	 * 
	 */
	public void show() {
		if (mode == SAVE) {
			rc = super.showSaveDialog(parent);
		} else {
			rc = super.showOpenDialog(parent);
		}
	}
}

class MyFileFilter extends javax.swing.filechooser.FileFilter {
	private FilenameFilter filter = null;
	public MyFileFilter(FilenameFilter filter) {
		this.filter = filter;
	}

	public boolean accept(java.io.File pathname) {
		java.io.File dir = pathname.getParentFile();
		String name = pathname.getName();
		return filter.accept(dir, name);
	}

	public String getDescription() {
		return "*.*";
	}
}
